/*
 * @Description: 自定义指令，一般用于操作dom元素
 * @Author: zyj
 * @Date: 2022-06-09 13:44:28
 * @LastEditors: zhanyinjia
 * @LastEditTime: 2022-11-21 10:29:20
 */
import Vue from 'vue'

function throttle(fn, delay) {
  let previous = 0
  const _this = this
  return function (args) {
    const _args = args
    const now = Date.now()
    if (now - previous > delay) {
      fn.call(_this, _args)
      previous = now
    }
  }
}

function debounce(fn, delay) {
  let timer = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.call(this, arguments)
    }, delay)
  }
}

export default {
  // 节流
  throttle: {
    inserted(el, binding) {
      let execFunc
      if (binding.value instanceof Array) {
        const [func, time = 500] = binding.value
        execFunc = throttle(func, time)
      } else {
        execFunc = throttle(binding.value, 500)
      }
      el._throttle = execFunc;
      el.addEventListener('click', el._throttle)
    },
    unbind(el) {
      el.removeEventListener("click", el._throttle);
    }
  },
  // 防抖
  debounce: {
    inserted: function (el, binding) {
      let execFunc
      if (binding.value instanceof Array) {
        const [func, time = 500] = binding.value
        execFunc = debounce(func, time)
      } else {
        execFunc = debounce(binding.value, 500)
      }
      el._debounce = execFunc;
      el.addEventListener('click', el._debounce)
    },
    unbind(el) {
      el.addEventListener("click", el._debounce)
    }
  },
  // 边框
  border: {
    inserted(el, binding) {
      el.style.border = `1px solid ${binding.value}`
    }
  },
  //按钮权限判断
  has: {
    inserted: function (el, binding) {
      if (!Vue.prototype.$has(binding.value)) {
        el.parentNode.removeChild(el);
      }
    }
  },
  // 点击元素范围外
  clickOutside: {
    inserted(el, binding, vNode) {
      document.addEventListener("click", (e) => {
        // 如果点击的不是当前元素内的就隐藏指定标签的元素
        if (!el.contains(e.target)) {
          vNode.context[binding.expression]()
        }
      })
    },
  },
  // 自动获焦
  focus: {
    inserted(el) {
      el.focus()
    }
  },
  textClick: {
    bind: function (el, binding) {
      el.style.color = "#3371FF"
      el.handler = () => {
        if (!Vue.prototype.$_has(binding.value[0])) {
          Vue.prototype.$message.warning('暂无权限');
        } else {
          binding.value[1]()
        }
      }
      el.addEventListener('click', el.handler)
    },
    unbind(el) {
      el.removeEventListener('click', el.handler)
    }
  }
}